"""
设备管理应用视图
"""
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse
from django.core.paginator import Paginator
from django.db.models import Q
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
import json

from .models import Device, DeviceBrand, DeviceType, PlatformCredential, DeviceCommand
from .forms import DeviceForm, DeviceBrandForm, DeviceTypeForm, PlatformCredentialForm


@login_required
def device_list(request):
    """设备列表页面"""
    devices = Device.objects.filter(owner=request.user).select_related('brand', 'device_type')
    
    # 搜索功能
    search_query = request.GET.get('search', '')
    if search_query:
        devices = devices.filter(
            Q(name__icontains=search_query) |
            Q(brand__name__icontains=search_query) |
            Q(device_type__name__icontains=search_query)
        )
    
    # 状态筛选
    status_filter = request.GET.get('status', '')
    if status_filter:
        devices = devices.filter(status=status_filter)
    
    # 分页
    paginator = Paginator(devices, 12)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
        'search_query': search_query,
        'status_filter': status_filter,
        'status_choices': Device.STATUS_CHOICES,
    }
    return render(request, 'devices/device_list.html', context)


@login_required
def device_add(request):
    """添加设备页面"""
    if request.method == 'POST':
        form = DeviceForm(request.POST, request.FILES)
        if form.is_valid():
            device = form.save(commit=False)
            device.owner = request.user
            device.save()
            messages.success(request, f'设备 "{device.name}" 添加成功！')
            return redirect('devices:device_list')
    else:
        form = DeviceForm()
    
    context = {
        'form': form,
        'title': '添加设备',
    }
    return render(request, 'devices/device_form.html', context)


@login_required
def device_detail(request, device_id):
    """设备详情页面"""
    device = get_object_or_404(Device, id=device_id, owner=request.user)
    
    # 获取设备最近的命令记录
    recent_commands = DeviceCommand.objects.filter(device=device).order_by('-created_at')[:10]
    
    context = {
        'device': device,
        'recent_commands': recent_commands,
    }
    return render(request, 'devices/device_detail.html', context)


@login_required
def device_edit(request, device_id):
    """编辑设备页面"""
    device = get_object_or_404(Device, id=device_id, owner=request.user)
    
    if request.method == 'POST':
        form = DeviceForm(request.POST, request.FILES, instance=device)
        if form.is_valid():
            form.save()
            messages.success(request, f'设备 "{device.name}" 更新成功！')
            return redirect('devices:device_detail', device_id=device.id)
    else:
        form = DeviceForm(instance=device)
    
    context = {
        'form': form,
        'device': device,
        'title': '编辑设备',
    }
    return render(request, 'devices/device_form.html', context)


@login_required
@require_http_methods(["POST"])
def device_delete(request, device_id):
    """删除设备"""
    device = get_object_or_404(Device, id=device_id, owner=request.user)
    device_name = device.name
    device.delete()
    messages.success(request, f'设备 "{device_name}" 删除成功！')
    return redirect('devices:device_list')


@login_required
@csrf_exempt
def device_control(request, device_id):
    """设备控制接口"""
    device = get_object_or_404(Device, id=device_id, owner=request.user)
    
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            command = data.get('command')
            parameters = data.get('parameters', {})
            
            # 创建设备命令记录
            device_command = DeviceCommand.objects.create(
                device=device,
                command=command,
                parameters=parameters,
                user=request.user
            )
            
            # TODO: 实际的设备控制逻辑
            # 这里应该调用具体的设备适配器来执行命令
            
            # 模拟命令执行
            device_command.status = 'completed'
            device_command.result = {'message': '命令执行成功'}
            device_command.save()
            
            return JsonResponse({
                'success': True,
                'message': '命令执行成功',
                'command_id': device_command.id
            })
            
        except Exception as e:
            return JsonResponse({
                'success': False,
                'message': f'命令执行失败: {str(e)}'
            }, status=400)
    
    return JsonResponse({'error': '不支持的请求方法'}, status=405)


@login_required
def brand_list(request):
    """设备品牌列表页面"""
    brands = DeviceBrand.objects.all().order_by('name')
    
    # 搜索功能
    search_query = request.GET.get('search', '')
    if search_query:
        brands = brands.filter(name__icontains=search_query)
    
    # 分页
    paginator = Paginator(brands, 20)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
        'search_query': search_query,
    }
    return render(request, 'devices/brand_list.html', context)


@login_required
def brand_add(request):
    """添加设备品牌页面"""
    if request.method == 'POST':
        form = DeviceBrandForm(request.POST, request.FILES)
        if form.is_valid():
            brand = form.save()
            messages.success(request, f'品牌 "{brand.name}" 添加成功！')
            return redirect('devices:brand_list')
    else:
        form = DeviceBrandForm()
    
    context = {
        'form': form,
        'title': '添加品牌',
    }
    return render(request, 'devices/brand_form.html', context)


@login_required
def brand_detail(request, brand_id):
    """设备品牌详情页面"""
    brand = get_object_or_404(DeviceBrand, id=brand_id)
    devices = Device.objects.filter(brand=brand, owner=request.user)
    
    context = {
        'brand': brand,
        'devices': devices,
    }
    return render(request, 'devices/brand_detail.html', context)


@login_required
def brand_edit(request, brand_id):
    """编辑设备品牌页面"""
    brand = get_object_or_404(DeviceBrand, id=brand_id)
    
    if request.method == 'POST':
        form = DeviceBrandForm(request.POST, request.FILES, instance=brand)
        if form.is_valid():
            form.save()
            messages.success(request, f'品牌 "{brand.name}" 更新成功！')
            return redirect('devices:brand_detail', brand_id=brand.id)
    else:
        form = DeviceBrandForm(instance=brand)
    
    context = {
        'form': form,
        'brand': brand,
        'title': '编辑品牌',
    }
    return render(request, 'devices/brand_form.html', context)


@login_required
@require_http_methods(["POST"])
def brand_delete(request, brand_id):
    """删除设备品牌"""
    brand = get_object_or_404(DeviceBrand, id=brand_id)
    brand_name = brand.name
    brand.delete()
    messages.success(request, f'品牌 "{brand_name}" 删除成功！')
    return redirect('devices:brand_list')


@login_required
def device_type_list(request):
    """设备类型列表页面"""
    device_types = DeviceType.objects.all().order_by('name')
    
    # 搜索功能
    search_query = request.GET.get('search', '')
    if search_query:
        device_types = device_types.filter(name__icontains=search_query)
    
    # 分页
    paginator = Paginator(device_types, 20)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
        'search_query': search_query,
    }
    return render(request, 'devices/device_type_list.html', context)


@login_required
def device_type_add(request):
    """添加设备类型页面"""
    if request.method == 'POST':
        form = DeviceTypeForm(request.POST)
        if form.is_valid():
            device_type = form.save()
            messages.success(request, f'设备类型 "{device_type.name}" 添加成功！')
            return redirect('devices:device_type_list')
    else:
        form = DeviceTypeForm()
    
    context = {
        'form': form,
        'title': '添加设备类型',
    }
    return render(request, 'devices/device_type_form.html', context)


@login_required
def device_type_detail(request, type_id):
    """设备类型详情页面"""
    device_type = get_object_or_404(DeviceType, id=type_id)
    devices = Device.objects.filter(device_type=device_type, owner=request.user)
    
    context = {
        'device_type': device_type,
        'devices': devices,
    }
    return render(request, 'devices/device_type_detail.html', context)


@login_required
def device_type_edit(request, type_id):
    """编辑设备类型页面"""
    device_type = get_object_or_404(DeviceType, id=type_id)
    
    if request.method == 'POST':
        form = DeviceTypeForm(request.POST, instance=device_type)
        if form.is_valid():
            form.save()
            messages.success(request, f'设备类型 "{device_type.name}" 更新成功！')
            return redirect('devices:device_type_detail', type_id=device_type.id)
    else:
        form = DeviceTypeForm(instance=device_type)
    
    context = {
        'form': form,
        'device_type': device_type,
        'title': '编辑设备类型',
    }
    return render(request, 'devices/device_type_form.html', context)


@login_required
@require_http_methods(["POST"])
def device_type_delete(request, type_id):
    """删除设备类型"""
    device_type = get_object_or_404(DeviceType, id=type_id)
    device_type_name = device_type.name
    device_type.delete()
    messages.success(request, f'设备类型 "{device_type_name}" 删除成功！')
    return redirect('devices:device_type_list')


@login_required
def credential_list(request):
    """平台凭证列表页面"""
    credentials = PlatformCredential.objects.filter(user=request.user).order_by('platform_name')
    
    # 搜索功能
    search_query = request.GET.get('search', '')
    if search_query:
        credentials = credentials.filter(platform_name__icontains=search_query)
    
    # 分页
    paginator = Paginator(credentials, 20)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
        'search_query': search_query,
    }
    return render(request, 'devices/credential_list.html', context)


@login_required
def credential_add(request):
    """添加平台凭证页面"""
    if request.method == 'POST':
        form = PlatformCredentialForm(request.POST)
        if form.is_valid():
            credential = form.save(commit=False)
            credential.user = request.user
            credential.save()
            messages.success(request, f'平台凭证 "{credential.platform_name}" 添加成功！')
            return redirect('devices:credential_list')
    else:
        form = PlatformCredentialForm()
    
    context = {
        'form': form,
        'title': '添加平台凭证',
    }
    return render(request, 'devices/credential_form.html', context)


@login_required
def credential_detail(request, credential_id):
    """平台凭证详情页面"""
    credential = get_object_or_404(PlatformCredential, id=credential_id, user=request.user)
    
    context = {
        'credential': credential,
    }
    return render(request, 'devices/credential_detail.html', context)


@login_required
def credential_edit(request, credential_id):
    """编辑平台凭证页面"""
    credential = get_object_or_404(PlatformCredential, id=credential_id, user=request.user)
    
    if request.method == 'POST':
        form = PlatformCredentialForm(request.POST, instance=credential)
        if form.is_valid():
            form.save()
            messages.success(request, f'平台凭证 "{credential.platform_name}" 更新成功！')
            return redirect('devices:credential_detail', credential_id=credential.id)
    else:
        form = PlatformCredentialForm(instance=credential)
    
    context = {
        'form': form,
        'credential': credential,
        'title': '编辑平台凭证',
    }
    return render(request, 'devices/credential_form.html', context)


@login_required
@require_http_methods(["POST"])
def credential_delete(request, credential_id):
    """删除平台凭证"""
    credential = get_object_or_404(PlatformCredential, id=credential_id, user=request.user)
    platform_name = credential.platform_name
    credential.delete()
    messages.success(request, f'平台凭证 "{platform_name}" 删除成功！')
    return redirect('devices:credential_list')
